package test;

//从中序和后序遍历序列中构造二叉树
 public class TreeNode2 {
     int val;
     TreeNode2 left;
     TreeNode2 right;
     TreeNode2() {}
     TreeNode2(int val) { this.val = val; }
 TreeNode2(int val, TreeNode2 left, TreeNode2 right) {
         this.val = val;
         this.left = left;
         this.right = right;
   }
 }
class Solution2 {
    public int postIndex;

    public TreeNode2 buildTree(int[] inorder, int[] postorder) {
        postIndex = postorder.length - 1;
        return buildTreeChild(inorder, postorder, 0, inorder.length - 1);
    }

    public TreeNode2 buildTreeChild(int[] inorder, int[] postorder, int inbegin, int inend) {
        // 这种情况下表明当前root没有子树了
        if (inbegin > inend) {
            return null;
        }
        TreeNode2 root = new TreeNode2(postorder[postIndex]);
        int rootIndex = findVal(inorder, inbegin, inend, postorder[postIndex]);
        postIndex--;

        root.right = buildTreeChild(inorder, postorder, rootIndex + 1, inend);

        root.left = buildTreeChild(inorder, postorder, inbegin, rootIndex - 1);
        return root;

    }

    private int findVal(int[] inorder, int inbegin, int inend, int val) {

        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }

}